<?php

namespace App\Services;
use App\Models\Goods;
use App\Models\Order;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use App\Services\OrderServices;
use App\Models\WxPayRecord;

class GoodsServices
{
    public function buy_goods($goods_id,$user_id){
        $order = DB::transaction(function ()use($goods_id,$user_id){
            //$goods = Goods::where('id',$goods_id)->lockForUpdate()->first();
            $goods = Goods::where('id',$goods_id)->first();
            if($goods->stock < 1){
                throw new \Exception('库存不足');
            }
            $order_price = $goods->goods_price + $goods->freight_price;
            $order = new Order([
                'goods_id'=>$goods->id,
                'user_id'=>$user_id,
                'order_price'=>$order_price,
                'goods_price'=>$goods->goods_price,
                'freight_price'=>$goods->freight_price,
                'stock_id'=>$goods->stock_id,
                'goods_name'=>$goods->goods_name,
                'order_number'=>getRandCode(32),
                'goods_cove'=>$goods->getOriginal('goods_cove'),
            ]);
            $add_result = $order->save();
            $update_result = $goods->decrement('stock');
            if($add_result && $update_result){
                return $order->id;
            }
            return false;
        },5);
        return $order;
    }

    public function push_goods_queue($goods_id){
        $redis = new Redis();
        $total_stock = Goods::where('id',$goods_id)->value('stock');
        //$redis->
    }

    public function pay_order($order_id,$user_id,$open_id){
        $order = DB::transaction(function ()use($order_id,$user_id,$open_id){
            //$goods = Goods::where('id',$goods_id)->lockForUpdate()->first();
            $order = Order::where('id',$order_id)->first();
            if($order->order_status != 1){
                throw new \Exception('该状态不能支付');
            }
            $notify_url = getDomain().'/api/user/wx_order_notify';
            $orderService = new OrderServices();
            $result = $orderService->pay_order($order_id,$open_id,$notify_url);
            if(empty($result)){
                throw new \Exception('统一下单失败');
            }
            $WxPayRecord = new WxPayRecord([
                'user_id'=>$user_id,
                'order_id'=>$order_id,
                'out_trade_no'=>$order->order_number,
                'status'=>3,
                'out_refund_no'=>getRandCode(32),
            ]);
            $add_result = $WxPayRecord->save();
            //$update_result = $goods->decrement('stock');
            return $result;
        },5);
        return $order;
    }
}